package com.ndhutu.ee.util.lock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @Author Shane
 * @Date 2020/7/26 0:55
 */
public class RedisLockUtil {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 加锁
     * @Author Shane
     * @Date 2020/7/26 1:58
     * @param
     * @return
     */
    public static boolean lock(String key, String id, StringRedisTemplate redisTemplate) throws Exception{
        boolean locked = false;

        do{
            locked = redisTemplate.opsForValue().setIfAbsent(key, id, 30, TimeUnit.SECONDS);
            if(!locked){
                Thread.sleep(200);
            }
        }while (!locked);

        return locked;
    }

    /**
     * 解锁
     * @Author Shane
     * @Date 2020/7/26 2:06
     * @param
     * @return
     */
    public static boolean unlock(String key, String id, StringRedisTemplate redisTemplate) throws Exception{
        boolean releaseLock = false;

        String reqId = redisTemplate.opsForValue().get(key);
        if(reqId.equals(id)){
            releaseLock = redisTemplate.delete(key);
        }

        return releaseLock;
    }
}
